package com.example.mytestdemo.miv

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @author tgw
 * @date 2022/9/5
 * @describe
 *
 * SharedFlow与StateFlow区别
 * https://juejin.cn/post/7054178311076839432
 *
 * mvi方式，
 */
class UiMviViewModel:ViewModel() {

    companion object{
        private const val TAG = "UiMviViewModel"
    }

    private val _state = MutableSharedFlow<MainUiState>(replay = 0, extraBufferCapacity = 0)
    val state: SharedFlow<MainUiState>
        get() = _state

    ///MutableStateFlow的格式
    private val _stateFlow = MutableStateFlow<MainUiState>(MainUiState.isLoading)
    val stateFlow: StateFlow<MainUiState>
        get() = _stateFlow

    //检测传统的写法
    val liveData = MutableLiveData<Boolean>()

    /**
     * 用于接收用户事件
     */
    private val userIntent = MutableSharedFlow<MainIntent>()


    /**
     * 分发用户事件
     * @param viewAction
     */
    fun dispatch(viewAction: MainIntent) {
        try {
            viewModelScope.launch {
                userIntent.emit(viewAction)
            }
        } catch (e: Exception) {
        }
    }


    private suspend fun refresh(param: MainIntent.refresh){
        _state.emit(MainUiState.isLoading)
        delay(3000)
        _state.emit(MainUiState.loadSuccess(ReqData().apply {
            name = "请求参数：${param.param}---刷新名称"
        }))
    }

    private suspend fun loadData(){
        _state.emit(MainUiState.isLoading)
        delay(3000)
        _state.emit(MainUiState.loadSuccess(ReqData().apply {
            name = "loadData 刷新名称"
        }))
    }

    private suspend fun loadFail(){
        _state.emit(MainUiState.isLoading)
        delay(3000)
        _state.emit(MainUiState.loadError(Exception("加载失败")))
    }


    init {
        viewModelScope.launch {
            userIntent.collect {
                Log.d(TAG, "用户行为更改: ")
                when (it) {
                    is MainIntent.refresh -> {
                        Log.d(TAG, "用户行为更改: refresh")
                        liveData.value = false
                        refresh(it)
                    }
                    is MainIntent.loadData ->{
                        Log.d(TAG, "用户行为更改: loadData")
                        loadData()
                    }

                    is MainIntent.loadFail ->{
                        Log.d(TAG, "用户行为更改: loadFail")
                        loadFail()
                    }
                    else -> {}
                }
            }
        }
    }
}